<?php


namespace app\admin\controller;


use app\admin\model\Code;
use app\BaseController;
use app\lib\Excel;
use app\Request;

class Setting extends  BaseController
{
    public function getCodes(Request  $request)
    {
        $isExport = $request->post('is_export');
        $page = $request->post('page', 1);
        $limit = $request->post('limit', 10);
        $status = $request->post('status');
        $where = [];
        if(!empty($this->userInfo['username']) && $this->userInfo['username'] !='admin'){
            $where['manager_id'] = $this->userInfo['id'];
        }
        $model  = \app\admin\model\Code::order('status asc, id desc')->where($where)->append(['status_text']);
        if (is_numeric($status)) {
            $model = $model->where('status', $status);
            $total = \app\admin\model\Code::where('status', $status)->where($where)->count();
        } else {
            $total = \app\admin\model\Code::where($where)->count();
        }

        if (empty($isExport)) {
            $result = $model->page($page, $limit)->select();
            //增加商户信息
            $result = \app\admin\model\Manager::getMananger($result);
            $data = [
                'total' => $total,
                'current' => $page,
                'perpage' => $limit,
                'data' =>  $result
            ];
        } else {
            $result = $model->select()->toArray();
            $excel = new Excel();
            //设置表格标题
            $title = [
                'code' => '兑换码',
                'status_text' => '是否兑换',
                'price' => '面值',
                'create_time' => '生成时间',
            ];
            //添加标题到数组头部
            array_unshift($result,$title);

            //根据此参数获取数据中的值，要与表格标题键名对应
            $keys = ['code','status_text','price' , 'create_time'];
            $excel->exportExcel($result,$keys,'卡密管理' . date('Y-m-d_His') . '.xlsx', [
                // 设置宽度
                'setWidth' => [
                    'A' => '20',
                    'B' => '20',
                    'C' => '20',
                    'D' => '30',
                    'E' => '30',
                    'F' => '30',
                    'G' => '30',
                    'H' => '30',
                ]
            ]);
            exit;
        }
        return show(config('status.success'), '操作成功', $data);
    }


    public function buildCode(Request $request)
    {
        $number = $request->post('number');
        $price   = $request->post('price');
        if ($number < 1) {
            return show(config('status.client_error'), '请输入生成的数量');
        }
        if ($number > 1000)  {
            return show(config('status.client_error'), '生成数量不得大于1000');
        }
        if ($price <= 0) {
            return show(config('status.client_error'), '面值金额必须大于0元');
        }

        $code = rand(100000, 999999);
        $list = range('A', 'Z');
        $datas = [];
        $curDate = date('Y-m-d H:i:s');
        $codes = [];
        for ($i = 0 ; $i < $number; $i++) {
            $tempCode = $this->buildUniqueCode($code, $list, $codes);
            $codes[] = $tempCode;
            $datas[] = [
                'code' => $tempCode,
                'price' => $price,
                'create_time' => $curDate,
                'manager_id' => $this->userInfo['id']??0,
            ];
        }

        Code::insertAll($datas);
        return show(config('status.success'), '操作成功');
    }

    private function buildUniqueCode(&$code, &$list, &$codes)
    {
        $first = array_rand($list, 1);
        $two = array_rand($list, 1);
        $three = array_rand($list, 1);
        $four = array_rand($list, 1);
        $tempCode = $list[$first] . $list[$two] . $list[$three] . $list[$four] .  $code;

        $codeObj = Code::where('code', $tempCode)->value('id');
        if (!empty($codeObj) || in_array($tempCode, $codes)) {
            return $this->buildUniqueCode($code, $list, $codes);
        }

        return $tempCode;
    }

    public function getContent()
    {
        $car_wash_tutorial = \app\admin\model\Setting::where('key', 'car_wash_tutorial')->value('value');
        $server_proto      = \app\admin\model\Setting::where('key', 'server_proto')->value('value');
        $about             = \app\admin\model\Setting::where('key', 'about')->value('value');
        $kf_phone          = \app\admin\model\Setting::where('key', 'kf_phone')->value('value');
        $recharge_protol   = \app\admin\model\Setting::where('key', 'recharge_protol')->value('value');
        $user_protol       = \app\admin\model\Setting::where('key', 'user_protol')->value('value');

        return show(config('status.success'), '操作成功', compact('car_wash_tutorial', 'server_proto', 'about', 'kf_phone', 'user_protol',  'recharge_protol'));
    }

    public function updateContent(Request $request)
    {
        \app\admin\model\Setting::where('key', 'car_wash_tutorial')->update([
            'value' => $request->post('car_wash_tutorial')
        ]);
        \app\admin\model\Setting::where('key', 'server_proto')->update([
            'value' => $request->post('server_proto')
        ]);
        \app\admin\model\Setting::where('key', 'about')->update([
            'value' => $request->post('about')
        ]);
        \app\admin\model\Setting::where('key', 'kf_phone')->update([
            'value' => $request->post('kf_phone')
        ]);
        \app\admin\model\Setting::where('key', 'recharge_protol')->update([
            'value' => $request->post('recharge_protol')
        ]);
        \app\admin\model\Setting::where('key', 'user_protol')->update([
            'value' => $request->post('user_protol')
        ]);
        return show(config('status.success'), '操作成功');
    }

    public function getListByPackage(Request  $request)
    {
        $page = $request->post('page', 1);
        $limit = $request->post('limit', 10);
        $where['store_id'] = $request->post('store_id');
        $where['manager_id'] = $this->userInfo['id'];
        $result = \app\admin\model\Package::order('id asc')->where($where)->page($page, $limit)->select();
        $total = \app\admin\model\Package::count();

        $data = [
            'total' => $total,
            'current' => $page,
            'perpage' => $limit,
            'data' =>  $result
        ];

        return show(config('status.success'), '操作成功', $data);
    }

    /**
     * 创建
     * @param Request $request
     * @return \think\response\Json
     */
    public function createByPackage(Request $request)
    {
        $result = \app\admin\model\Package::create([
            'store_id' => $request->post('store_id'),
            'manager_id' => $this->userInfo['id'],
            'price' => $request->post('price'),
            'send_price' => $request->post('send_price'),
            'sort' => $request->post('sort', 0)
        ]);
        return show(config('status.success'), '操作成功', [
            'id' => (int) $result->id
        ]);
    }

    /**
     * 更新
     * @param Request $request
     * @return \think\response\Json
     */
    public function updateByPackage(Request $request)
    {
        \app\admin\model\Package::where(['id' => $request->post('id')])->update([
            'price' => $request->post('price'),
            'send_price' => $request->post('send_price'),
            'sort'       => $request->post('sort', 0)
        ]);

        return show(config('status.success'), '操作成功');
    }

    public function deleteByPackage(Request  $request)
    {
        \app\admin\model\Package::destroy($request->post('id'));
        return show(config('status.success'), '操作成功');
    }
}